package cn.xspace.module.other.http.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;

import com.xspace.android.xafcommon.network.NetConstant;
import com.xspace.android.xafcommon.network.message.AResponseMsg;
import com.xspace.android.xafcommon.network.message.SendRequestListener;
import cn.xspace.library.util.MyInfoUtil;
import com.xspace.android.xafcommon.util.StringUtils;
import cn.xspace.library.util.Tools;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import cn.xspace.module.other.http.NetControl;
import cn.xspace.module.other.http.intface.IUpgrade;
import cn.xspace.module.other.http.resp.UpgradeResp;
import cn.xspace.module.other.util.RProxy;

/**
 * @version V1.0.0
 * @ClassName: UpdateManage
 * @author:qbluo
 * @Date：2013-7-19
 * @Description: TODO
 */
public class UpgradeImpl implements IUpgrade, SendRequestListener {
    private NetControl mNetControl;
    private Context mContext;
    IUpdateRequest mCallBack;
    boolean flag = false;

    public UpgradeImpl(Context mContext) {
        this.mContext = mContext;
        mNetControl = new NetControl(this);
    }

    @Override
    public void updateCheck(boolean flag, String user_id, String departmentID, String app_id, String area, IUpdateRequest mCallBack) {
        this.mCallBack = mCallBack;
        this.flag = flag;
        try {

            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
            String phone = Tools.getCurrentAccountInfo(mContext).mobile;

            mNetControl.sendUpdate(user_id, departmentID, phone, app_id, tm.getDeviceId(), getBaseBand(),
                    android.os.Build.VERSION.RELEASE, android.os.Build.PRODUCT, getMacAddress(), getCpuInfo(),
                    MyInfoUtil.getAppInfo(mContext).app_version, area);
        } catch (Exception e) {
//			MobclickAgent.reportError(MyApplication.mContext, e);
            e.printStackTrace();
        }

    }

    public static String getCpuInfo() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String[] cpuInfo = {"", ""};
        String[] arrayOfString;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            for (int i = 2; i < arrayOfString.length; i++) {
                cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
            }
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            cpuInfo[1] += arrayOfString[2];
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cpuInfo[0] + cpuInfo[1];
    }

    private String getMacAddress() {
        String result = "";
        try {
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            result = wifiInfo.getMacAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public String getBaseBand() {
        String result = "";
        try {
            Class cl = Class.forName("android.os.SystemProperties");
            Object invoker = cl.newInstance();
            Method m = cl.getMethod("get", new Class[]{String.class, String.class});
            result = (String) m.invoke(invoker, new Object[]{"gsm.version.baseband", "no message"});

        } catch (Exception e) {
        }
        return result;

    }

    @Override
    public void requestResult(int result, AResponseMsg object) {
        Log.v("cover", "coverresult:" + result + " object.msgType:" + object.msgType);
        if (NetControl.MSGTYPE_UPDATE.equals(object.msgType)) {
            UpgradeResp resp = (UpgradeResp) object;
            Log.v("cover", "resp.code:" + resp.code);
            if (result == NetConstant.TaskStatus.SUCCESS && resp.code.equals("0")) {
                if (resp.result == null) {
					//已是最新
                    if (flag) {
                        Toast.makeText(mContext, RProxy.msg_update_new_date_over, Toast.LENGTH_SHORT).show();
                    }
                    mCallBack.onResult(null, null, "0");
                    return ;
                }
                if (resp != null && resp.result != null && StringUtils.isEmpty(resp.result.tag))
                    resp.result.tag = "0";
                if (resp.result != null && !StringUtils.isEmpty(resp.result.app_id)) {
                    //Log.v("cover", "resp.result.app_id:"+resp.result.app_id+" localid:" +AppCache.getAppConfigBean(mContext).appID);
                    if (!resp.result.app_id.equalsIgnoreCase(MyInfoUtil.getAppInfo(mContext).app_id)) {
                        mCallBack.onResult(resp.result.note, resp.result.url, resp.result.tag);
                    } else {
                        if (flag) {
                            Toast.makeText(mContext, RProxy.msg_update_new_date_over, Toast.LENGTH_SHORT).show();
                        }
                    }
                    mCallBack.onResult(null, null, resp.result.tag);
                } else {
                    if (flag) {
                        Toast.makeText(mContext, RProxy.msg_update_new_date_over, Toast.LENGTH_SHORT).show();
                    }
                    mCallBack.onResult(null, null, "0");
                }

            } else {
                if (flag) {
                    Toast.makeText(mContext, RProxy.network_fail, Toast.LENGTH_SHORT).show();
                }
                mCallBack.onResult(null, null, "0");
            }
        }
    }

    public interface IUpdateRequest {
        public void onResult(String note, String url, String tag);
    }

    @Override
    public void offline(String arg0) {
        if (flag) {
            Toast.makeText(mContext, RProxy.network_fail, Toast.LENGTH_SHORT).show();
        }
        mCallBack.onResult(null, null, "0");
    }

}
